using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using Csla.Validation;

namespace PackTracker.Business
{ 
	[Serializable()] 
	public class Pedido : Csla.BusinessBase<Pedido>
	{
		#region Business Properties and Methods

		//declare members
		private int _id = 0;
		private SmartDate _data = new SmartDate(DateTime.Today);
		private SmartDate _dataEntrega = new SmartDate(false);
		private int _idVeiculo = 0;
		private int _idOrigem = 0;
		private int _idDestino = 0;

		//declare borrowed child member(s)
		private string _idOrigemLogradouro;
		private string _idDestinoLogradouro;

		[System.ComponentModel.DataObjectField(true, true)]
		public int Id
		{
			get
			{
				CanReadProperty("Id", true);
				return _id;
			}
		}

		public DateTime Data
		{
			get
			{
				CanReadProperty("Data", true);
				return _data.Date;
			}
		}

		public string DataString
		{
			get
			{
				CanReadProperty("DataString", true);
				return _data.Text;
			}
			set
			{
				CanWriteProperty("DataString", true);
				if (value == null) value = string.Empty;
				if (!_data.Equals(value))
				{
					_data.Text = value;
					PropertyHasChanged("DataString");
				}
			}
		}

		public DateTime DataEntrega
		{
			get
			{
				CanReadProperty("DataEntrega", true);
				return _dataEntrega.Date;
			}
		}

		public string DataEntregaString
		{
			get
			{
				CanReadProperty("DataEntregaString", true);
				return _dataEntrega.Text;
			}
			set
			{
				CanWriteProperty("DataEntregaString", true);
				if (value == null) value = string.Empty;
				if (!_dataEntrega.Equals(value))
				{
					_dataEntrega.Text = value;
					PropertyHasChanged("DataEntregaString");
				}
			}
		}

		public int IdVeiculo
		{
			get
			{
				CanReadProperty("IdVeiculo", true);
				return _idVeiculo;
			}
			set
			{
				CanWriteProperty("IdVeiculo", true);
				if (!_idVeiculo.Equals(value))
				{
					_idVeiculo = value;
					PropertyHasChanged("IdVeiculo");
				}
			}
		}

		public int IdOrigem
		{
			get
			{
				CanReadProperty("IdOrigem", true);
				return _idOrigem;
			}
			set
			{
				CanWriteProperty("IdOrigem", true);
				if (!_idOrigem.Equals(value))
				{
					_idOrigem = value;
					PropertyHasChanged("IdOrigem");
				}
			}
		}

		public int IdDestino
		{
			get
			{
				CanReadProperty("IdDestino", true);
				return _idDestino;
			}
			set
			{
				CanWriteProperty("IdDestino", true);
				if (!_idDestino.Equals(value))
				{
					_idDestino = value;
					PropertyHasChanged("IdDestino");
				}
			}
		}

		public string idOrigemLogradouro
		{
			get
			{
				CanReadProperty("idOrigemLogradouro", true);
				return _idOrigemLogradouro;
			}
		}

		public string idDestinoLogradouro
		{
			get
			{
				CanReadProperty("idDestinoLogradouro", true);
				return _idDestinoLogradouro;
			}
		}
 
		protected override object GetIdValue()
		{
			return _id;
		}

		#endregion //Business Properties and Methods

		#region Validation Rules
		private void AddCustomRules()
		{
			//add custom/non-generated rules here...
		}

		private void AddCommonRules()
		{
			//
			// Data
			//
			ValidationRules.AddRule(CommonRules.StringRequired, "DataString");
			//
			// IdOrigem
			//
			ValidationRules.AddRule(CommonRules.IntegerMinValue, new CommonRules.IntegerMinValueRuleArgs("IdOrigem", 1));
			//
			// IdDestino
			//
			ValidationRules.AddRule(CommonRules.IntegerMinValue, new CommonRules.IntegerMinValueRuleArgs("IdDestino", 1));
		}

		protected override void AddBusinessRules()
		{
			AddCommonRules();
			AddCustomRules();
		}
		#endregion //Validation Rules

		#region Authorization Rules
		protected override void AddAuthorizationRules()
		{
			//TODO: Define authorization rules in Pedido
			//AuthorizationRules.AllowRead("Id", "PedidoReadGroup");
			//AuthorizationRules.AllowRead("Data", "PedidoReadGroup");
			//AuthorizationRules.AllowRead("DataString", "PedidoReadGroup");
			//AuthorizationRules.AllowRead("DataEntrega", "PedidoReadGroup");
			//AuthorizationRules.AllowRead("DataEntregaString", "PedidoReadGroup");
			//AuthorizationRules.AllowRead("IdVeiculo", "PedidoReadGroup");
			//AuthorizationRules.AllowRead("IdOrigem", "PedidoReadGroup");
			//AuthorizationRules.AllowRead("IdDestino", "PedidoReadGroup");

			//AuthorizationRules.AllowWrite("DataString", "PedidoWriteGroup");
			//AuthorizationRules.AllowWrite("DataEntregaString", "PedidoWriteGroup");
			//AuthorizationRules.AllowWrite("IdVeiculo", "PedidoWriteGroup");
			//AuthorizationRules.AllowWrite("IdOrigem", "PedidoWriteGroup");
			//AuthorizationRules.AllowWrite("IdDestino", "PedidoWriteGroup");
		}


		public static bool CanGetObject()
		{
			//TODO: Define CanGetObject permission in Pedido
			return true;
			//if (Csla.ApplicationContext.User.IsInRole("PedidoViewGroup"))
			//	return true;
			//return false;
		}

		public static bool CanAddObject()
		{
			//TODO: Define CanAddObject permission in Pedido
			return true;
			//if (Csla.ApplicationContext.User.IsInRole("PedidoAddGroup"))
			//	return true;
			//return false;
		}

		public static bool CanEditObject()
		{
			//TODO: Define CanEditObject permission in Pedido
			return true;
			//if (Csla.ApplicationContext.User.IsInRole("PedidoEditGroup"))
			//	return true;
			//return false;
		}

		public static bool CanDeleteObject()
		{
			//TODO: Define CanDeleteObject permission in Pedido
			return true;
			//if (Csla.ApplicationContext.User.IsInRole("PedidoDeleteGroup"))
			//	return true;
			//return false;
		}
		#endregion //Authorization Rules

		#region Factory Methods
		private Pedido()
		{ /* require use of factory method */ }

		public static Pedido NewPedido()
		{
			if (!CanAddObject())
				throw new System.Security.SecurityException("User not authorized to add a Pedido");
			return DataPortal.Create<Pedido>();
		}

		public static Pedido GetPedido(int id)
		{
			if (!CanGetObject())
				throw new System.Security.SecurityException("User not authorized to view a Pedido");
			return DataPortal.Fetch<Pedido>(new Criteria(id));
		}

		public static void DeletePedido(int id)
		{
			if (!CanDeleteObject())
				throw new System.Security.SecurityException("User not authorized to remove a Pedido");
			DataPortal.Delete(new Criteria(id));
		}

		public override Pedido Save()
		{
			if (IsDeleted && !CanDeleteObject())
				throw new System.Security.SecurityException("User not authorized to remove a Pedido");
			else if (IsNew && !CanAddObject())
				throw new System.Security.SecurityException("User not authorized to add a Pedido");
			else if (!CanEditObject())
				throw new System.Security.SecurityException("User not authorized to update a Pedido");

			return base.Save();
		}

		#endregion //Factory Methods

		#region Child Factory Methods
		internal static Pedido NewPedidoChild()
		{
			Pedido child = new Pedido();
			child.ValidationRules.CheckRules();
			child.MarkAsChild();
			return child;
		}

		internal static Pedido GetPedido(SafeDataReader dr)
		{
			Pedido child =  new Pedido();
			child.MarkAsChild();
			child.Fetch(dr);
			return child;
		}
		#endregion //Child Factory Methods

		#region Data Access

		#region Criteria

		[Serializable()]
		private class Criteria
		{
			public int Id;

			public Criteria(int id)
			{
				this.Id = id;
			}
		}

		#endregion //Criteria

		#region Data Access - Create
		[RunLocal]
		protected override void DataPortal_Create()
		{
			ValidationRules.CheckRules();
		}

		#endregion //Data Access - Create

		#region Data Access - Fetch
		private void DataPortal_Fetch(Criteria criteria)
		{
			using (SqlConnection cn = new SqlConnection(Database.DefaultConnection))
			{
				cn.Open();

				ExecuteFetch(cn, criteria);
			}//using
		}

		private void ExecuteFetch(SqlConnection cn, Criteria criteria)
		{
			using (SqlCommand cm = cn.CreateCommand())
			{
				cm.CommandType = CommandType.StoredProcedure;
				cm.CommandText = "pr_GetPedido";
				cm.Parameters.AddWithValue("@id", criteria.Id);

				using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
				{
					dr.Read();
					FetchObject(dr);
					ValidationRules.CheckRules();

					//load child object(s)
					FetchChildren(dr);
				}
			}//using
		}

		#endregion //Data Access - Fetch

		#region Data Access - Insert
		protected override void DataPortal_Insert()
		{
			using (SqlConnection cn = new SqlConnection(Database.DefaultConnection))
			{
				cn.Open();

				ExecuteInsert(cn);

				//update child object(s)
				UpdateChildren(cn);
			}//using

		}

		#endregion //Data Access - Insert

		#region Data Access - Update
		protected override void DataPortal_Update()
		{
			using (SqlConnection cn = new SqlConnection(Database.DefaultConnection))
			{
				cn.Open();

				if (base.IsDirty)
				{
					ExecuteUpdate(cn);
				}

				//update child object(s)
				UpdateChildren(cn);
			}//using

		}

		#endregion //Data Access - Update

		#region Data Access - Delete
		protected override void DataPortal_DeleteSelf()
		{
			DataPortal_Delete(new Criteria(_id));
		}

		private void DataPortal_Delete(Criteria criteria)
		{
			using (SqlConnection cn = new SqlConnection(Database.DefaultConnection))
			{
				cn.Open();

				ExecuteDelete(cn, criteria);

			}//using

		}

		private void ExecuteDelete(SqlConnection cn, Criteria criteria)
		{
			using (SqlCommand cm = cn.CreateCommand())
			{
				cm.CommandType = CommandType.StoredProcedure;
				cm.CommandText = "pr_DeletePedido";

				cm.Parameters.AddWithValue("@id", criteria.Id);

				cm.ExecuteNonQuery();
			}//using
		}
		#endregion //Data Access - Delete

		#region Data Access - Fetch
		private void Fetch(SafeDataReader dr)
		{
			FetchObject(dr);
			MarkOld();
			ValidationRules.CheckRules();

			//load child object(s)
			if(!this.IsChild)
				FetchChildren(dr);
		}

		private void FetchObject(SafeDataReader dr)
		{
			_id = dr.GetInt32("id");
			_data = dr.GetSmartDate("Data", _data.EmptyIsMin);
			_dataEntrega = dr.GetSmartDate("DataEntrega", _dataEntrega.EmptyIsMin);
			_idVeiculo = dr.GetInt32("idVeiculo");
			_idOrigem = dr.GetInt32("idOrigem");
			_idDestino = dr.GetInt32("idDestino");
			_idOrigemLogradouro = dr.GetString("idOrigemLogradouro");
			_idDestinoLogradouro = dr.GetString("idDestinoLogradouro");
		}

		private void FetchChildren(SafeDataReader dr)
		{
		}
		#endregion //Data Access - Fetch

		#region Data Access - Insert
		internal void Insert(SqlConnection cn)
		{
			if (!IsDirty) return;

			ExecuteInsert(cn);
			MarkOld();

			//update child object(s)
			UpdateChildren(cn);
		}

		private void ExecuteInsert(SqlConnection cn)
		{
			using (SqlCommand cm = cn.CreateCommand())
			{
				cm.CommandType = CommandType.StoredProcedure;
				cm.CommandText = "pr_AddPedido";

				AddInsertParameters(cm);

				cm.ExecuteNonQuery();

				_id = (int)cm.Parameters["@id"].Value;
			}//using
		}

		private void AddInsertParameters(SqlCommand cm)
		{
			cm.Parameters.AddWithValue("@Data", _data.DBValue);
			if (_dataEntrega != new SmartDate(false))
				cm.Parameters.AddWithValue("@DataEntrega", _dataEntrega.DBValue);
			else
				cm.Parameters.AddWithValue("@DataEntrega", DBNull.Value);
			if (_idVeiculo != 0)
				cm.Parameters.AddWithValue("@idVeiculo", _idVeiculo);
			else
				cm.Parameters.AddWithValue("@idVeiculo", DBNull.Value);
			cm.Parameters.AddWithValue("@idOrigem", _idOrigem);
			cm.Parameters.AddWithValue("@idDestino", _idDestino);
			cm.Parameters.AddWithValue("@id", _id);
			cm.Parameters["@id"].Direction = ParameterDirection.Output;
		}
		#endregion //Data Access - Insert

		#region Data Access - Update
		internal void Update(SqlConnection cn)
		{
			if (!IsDirty) return;

			if (base.IsDirty)
			{
				ExecuteUpdate(cn);
				MarkOld();
			}

			//update child object(s)
			UpdateChildren(cn);
		}

		private void ExecuteUpdate(SqlConnection cn)
		{
			using (SqlCommand cm = cn.CreateCommand())
			{
				cm.CommandType = CommandType.StoredProcedure;
				cm.CommandText = "pr_UpdatePedido";

				AddUpdateParameters(cm);

				cm.ExecuteNonQuery();

			}//using
		}

		private void AddUpdateParameters(SqlCommand cm)
		{
			cm.Parameters.AddWithValue("@id", _id);
			cm.Parameters.AddWithValue("@Data", _data.DBValue);
			if (_dataEntrega != new SmartDate(false))
				cm.Parameters.AddWithValue("@DataEntrega", _dataEntrega.DBValue);
			else
				cm.Parameters.AddWithValue("@DataEntrega", DBNull.Value);
			if (_idVeiculo != 0)
				cm.Parameters.AddWithValue("@idVeiculo", _idVeiculo);
			else
				cm.Parameters.AddWithValue("@idVeiculo", DBNull.Value);
			cm.Parameters.AddWithValue("@idOrigem", _idOrigem);
			cm.Parameters.AddWithValue("@idDestino", _idDestino);
		}

		private void UpdateChildren(SqlConnection cn)
		{
		}
		#endregion //Data Access - Update

		#region Data Access - Delete
		internal void DeleteSelf(SqlConnection cn)
		{
			if (!IsDirty) return;
			if (IsNew) return;

			ExecuteDelete(cn, new Criteria(_id));
			MarkNew();
		}
		#endregion //Data Access - Delete
		#endregion //Data Access
	}
}
